package com.vue.vue.service.impl;


import com.vue.vue.dao.UserMapper;
import com.vue.vue.enums.ResponseEnum;
import com.vue.vue.enums.RoleEnum;
import com.vue.vue.pojo.User;
import com.vue.vue.service.IUserService;
import com.vue.vue.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;


@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public ResponseVo<User> register(User user) {

        //用户名检查
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if (countByUsername > 0) {
//            throw new RuntimeException("该用户名已经注册");
            return ResponseVo.error(ResponseEnum.USERNAME_EXIST);
        }

        //email检查
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if (countByEmail > 0) {
//            throw new RuntimeException("该email已经注册");
            return ResponseVo.error(ResponseEnum.EMAIL_EXIST);

        }

        user.setRole(RoleEnum.CUSTOMER.getCode());
        //MD5加密校验 Spring自带
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(md5DigestAsHex);

        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount == 0){
//            throw new RuntimeException("注册失败");
            return ResponseVo.error(ResponseEnum.ERROR);
        }

        return ResponseVo.success();

    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if(user == null){
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);

        }
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!user.getPassword().equalsIgnoreCase(md5DigestAsHex)){
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        user.setPassword("");
        return ResponseVo.success(user);
    }

    @Override
    public List<User> selectAll() {
        //列表查询测试数据
        List<User> users = userMapper.selectUsers();
        return users;
    }


}
